package com.example.aicloud.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.aicloud.config.ThreadPoolConfig;
import com.example.aicloud.entity.Discuss;
import com.example.aicloud.entity.DiscussSupport;
import com.example.aicloud.entity.User;
import com.example.aicloud.entity.vo.CommentVO;
import com.example.aicloud.entity.vo.DiscussVO;
import com.example.aicloud.service.CommentService;
import com.example.aicloud.service.DiscussService;
import com.example.aicloud.service.DiscussSupportService;
import com.example.aicloud.service.UserService;
import com.example.aicloud.util.AppVariable;
import com.example.aicloud.util.ResponseEntity;
import com.example.aicloud.util.SecutiryUtil;
import jakarta.annotation.Resource;

import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 讨论表控制器
 */
@RestController
@RequestMapping("/discuss")
public class DiscussController {

    @Resource
    private DiscussService discussService;

    @Resource
    private ThreadPoolTaskExecutor threadPool;

    @Resource
    private UserService userService;

    @Resource
    private CommentService commentService;

    @Resource
    private KafkaTemplate kafkaTemplate;

    @Resource
    private DiscussSupportService discussSupportService;


    /**
     * 查询讨论详情
     */
    @RequestMapping("/detail")
    public ResponseEntity detail(Long did) throws ExecutionException, InterruptedException {
        if (did == null || did <= 0) return ResponseEntity.fail("参数错误！");
        Discuss discuss = discussService.getById(did);
        if (discuss != null && discuss.getDid() > 0) {
            // 添加阅读量
            threadPool.submit(() -> {
//                discuss.setReadcount(discuss.getReadcount() + 1);
//                discussService.saveOrUpdate(discuss);
                // 1.更新数据(阅读量+1)
                discussService.updateReadCount(did);
//                 2.返回对象阅读数+1
                discuss.setReadcount(discuss.getReadcount() + 1);
            });
            // 任务1：查询 discuss 中的 username
            CompletableFuture<DiscussVO> task = CompletableFuture.supplyAsync(() -> {
                // 对象转换
                DiscussVO discussVO = BeanUtil.toBean(discuss, DiscussVO.class);
                User user = userService.getById(discuss.getUid());
                if (user != null && user.getUid() > 0) {
                    discussVO.setUsername(user.getUsername());
                }
                return discussVO;
            }, threadPool);
            // 任务2：查询 discuss 所对应的 comment 列表
            CompletableFuture<List<CommentVO>> task2 = CompletableFuture.supplyAsync(() -> {
                return commentService.getCommentList(did);
            }, threadPool);
            CompletableFuture.allOf(task, task2);
            HashMap<String, Object> result = new HashMap<>();
            result.put("discuss", task.get());
            result.put("commentlist", task2.get());
            return ResponseEntity.succ(result);
        }
        return ResponseEntity.fail("该讨论不存在！");
    }

    /**
     * 添加话题讨论
     */
    @RequestMapping("/add")
    public ResponseEntity add(@Validated Discuss discuss) {
        discuss.setUid(SecutiryUtil.getCurrentUser().getUid());
        discuss.setReadcount(0);
        discuss.setSupportcount(0);
        boolean save = discussService.save(discuss);
        if (save) {
            return ResponseEntity.succ(save);
        }
        return ResponseEntity.fail("保存失败，请重试！");
    }

    /**
     * 获取我的讨论列表
     */
    @RequestMapping("/mylist")
    public ResponseEntity getMyList() {
        return ResponseEntity.succ(discussService.list(
                Wrappers.lambdaQuery(Discuss.class)
                        .eq(Discuss::getUid, SecutiryUtil.getCurrentUser().getUid())
                        .orderByDesc(Discuss::getDid)
        ));
    }

    /**
     * 讨论删除
     */
    @RequestMapping("/delete")
    public ResponseEntity delete(Long did) {
        if (did == null || did <= 0) return ResponseEntity.fail("参数错误！");
        boolean result = discussService.remove(
                Wrappers.lambdaQuery(Discuss.class)
                        .eq(Discuss::getDid, did)
                        .eq(Discuss::getUid, SecutiryUtil.getCurrentUser().getUid())
        );
        if (result) {
            return ResponseEntity.succ(result);
        }
        return ResponseEntity.fail("删除失败，请重试！");
    }

    /**
     * 讨论表点赞事件
     */
    @RequestMapping("/support")
    public ResponseEntity support(Long did) {
        if (did == null || did <= 0) return ResponseEntity.fail("参数错误！");
        kafkaTemplate.send(AppVariable.DISCUSS_SUPPORT_TOPIC, did + "_" +
                SecutiryUtil.getCurrentUser().getUid());
        return ResponseEntity.succ(true);
    }


    /**
     * 监听 Kafka 中的点赞事件
     */
    @KafkaListener(topics = {AppVariable.DISCUSS_SUPPORT_TOPIC})
    public void listen(String data, Acknowledgment acknowledgment) {
        // 0.判断当前登录用户是否给当前讨论表点赞过
        Long did = Long.parseLong(data.split("_")[0]);
        Long uid = Long.parseLong(data.split("_")[1]);
        List<DiscussSupport> list = discussSupportService.list(Wrappers.lambdaQuery(DiscussSupport.class)
                .eq(DiscussSupport::getDid, did)
                .eq(DiscussSupport::getUid, uid)
        );
        if (list == null || list.size() == 0) {
            // 1.修改讨论表点赞数
            int result = discussService.updateSupportCount(did);
            if (result > 0) {
                // 2.在点赞详情表中添加点赞消息
                DiscussSupport discussSupport = new DiscussSupport();
                discussSupport.setDid(did);
                discussSupport.setUid(uid);
                boolean save = discussSupportService.save(discussSupport);
                if (save) {
                    // 确认消息被接受
                    acknowledgment.acknowledge();
                }
            }
        }
    }


    /**
     * 获取讨论列表（带分页的）
     *
     * @param currentPage 当前第几页
     * @param type 1：推荐（点赞数排序），2：最新时间排序
     */
    @RequestMapping("/list")
    public ResponseEntity list(Integer currentPage, Integer type) {
        // 参数预处理
        if (currentPage == null || currentPage <= 0) currentPage = 1;
        if (type == null || type <= 0) type = 1;
        QueryWrapper<Discuss> queryWrapper = new QueryWrapper<>();
        if (type == 1) { // 根据点赞数进行排序
            queryWrapper.orderByDesc("supportcount");
        } else { // 根据创建时间排序
            queryWrapper.orderByDesc("did");
        }
        Page<Discuss> result = discussService.page(new Page<>(currentPage, AppVariable.PAGE_SIZE),
                queryWrapper);
        return ResponseEntity.succ(result);
    }

}
